import $ from 'jquery';

// let baseUrl = "http://114.116.89.115:8380";
let baseUrl = "http://127.0.0.1:8380";

async function request(options) {
    var patt = /^((ht|f)tps?):\/\//;
    let url;
    if (patt.test(options['url'])) {
        url = options['url'];
    } else {
        url = baseUrl + options['url'];
    }
    const resp = await fetch(url, {
        method: options['method'],
        body: options['data'],
        mode: 'cors',
        credentials: 'include'
    });
    if (resp.status == 200) {
        options['success'](await resp.json());
    } else {
        options['error'](await resp.text());
    }
}

function tajax(options) {
    var patt = /^((ht|f)tps?):\/\//;
    let url;
    if (patt.test(options['url'])) {
        url = options['url'];
    } else {
        url = baseUrl + options['url'];
    }

    $.ajax({
        url: url,
        method: options['method'],
        data: options['data'],
        success: function (data) {
            if (data.code === 0) {
                options['success'](data);
            } else if (data.code === 401) {
                window.location.href = '/login';
            } else if (data.code === 403) {
                options['unauth']();
            } else {
                options['error'](data);
            }
        },
        error: function (data) {
            if (data.status === 401) {
                window.location.href = '/login';
            } else if (data.status === 403) {
                options['unauth']();
            } else {
                options['error'](data)
            }

        },
        beforeSend: function (xhr) {
            xhr.withCredentials = true;
            xhr.setRequestHeader('Token', localStorage.getItem('Token'));
        },
        crossDomain: true
    });
}

export { request, tajax, baseUrl };